<?php
namespace x;
class Xbase{
    public $post = [];
    public $get = [];
    public $db;
    public $db1;
    public $template;
    public $m;
    public $c;
    public $a;

    //架构函数
    public function __construct(){
        #变量
        $this->post = G::$post;
        $this->get  = G::$get;

        #数据库
        $this->db  = G::$db;
        $this->db1 = G::$db1;

        #默认模板
        $app   = Container::get(App::class);
        $this->m = $app->m;
        $this->c = $app->c;
        $this->a = $app->a;
    }
    //显示模板
    public function fetch($vars=[],$template='', $layout='layout'){
        $vars = array_merge(G::$front_data,$vars);
        $template = $template ? $template : "$this->c/$this->a";
        $template = "$this->m/view/".$template;
        // 页面缓存
        ob_start();
        ob_implicit_flush(0);
        // 渲染输出
        try {
            if($layout){
                $vars['inc_sub_template'] = APP_PATH.$template.".html";
                extract($vars, EXTR_OVERWRITE);
                include_once APP_PATH."$this->m/view/".$layout.".html";
            }else{
                extract($vars, EXTR_OVERWRITE);
                include APP_PATH.$template.".html";
            }
        } catch (\Exception $e) {
            ob_end_clean();
            throw $e;
        }
        // 获取并清空缓存
        $content = ob_get_clean();
        exit($content);
    }

    //传递变量
    public function assign($name='', $val=''){
        if(is_array($name)){
            G::$front_data = array_merge(G::$front_data, $name);
        }else{
            G::$front_data = array_merge(G::$front_data, [$name=>$val]);
        }
    }
    //设置错误
    public function setError($value,$name=''){
        $name = $name ? $name : rand(1000,9999);
        G::$error_data[$name] = $value;
    }
    //获取错误
    public function getError(){
        cookie('js_name',key(G::$error_data));
        return end(G::$error_data);
    }
    //获取get变量
    public function get($key='',$default=''){
        if(empty($key)) return $this->get;
        if(!isset($this->get[$key]))
            return $default;
        return $this->get[$key];
    }
    //获取POST变量
    public function post($key='',$default=''){
        if(empty($key)) return $this->post;
        if(!isset($this->post[$key]))
            return $default;
        return $this->post[$key];
    }
}
